﻿@using si.caha.Model;
@using si.caha.Repository;

@{
    var category = PageData["category"];
    var errors = PageData["errors"];
    var dataContext = new DataContext();

    var categoryRepository = new CategoryRepository(dataContext);
    var parentCategory = categoryRepository.Get(category.CategoryParentId);

    if(IsPost)
    {
        category.Title = Request["title"];
        int categoryParentId = Request["CategoryParentId"].AsInt();

        var level = 0;
        if (categoryParentId > 0)
        {
            // level is one higher than a level of it's over-category
            var levelOfHigherCategory = categoryRepository.Get(categoryParentId).Level;
            level = levelOfHigherCategory + 1;
        }
        category.Level = level;
        category.CategoryParentId = categoryParentId;
        
        errors = categoryRepository.Save(category);
        
        if (errors.Count == 0)
        {
            Response.Redirect("~/Admin/Categories");
        }
    }
}
<fieldset>
    <legend>Create category</legend>
    <form method="post" action="">
        <div>
            <label for="title">Title:</label>
            <input id="title" name="title" type="text" autofocus="autofocus" value="@category.Title" />
            @if (errors.ContainsKey("Title"))
            {
                <span>@errors["Title"]</span>
            }
        </div>
        <div>
            <label for="CategoryParentId">Sub category of:</label>
            <select id="CategoryParentId" name="CategoryParentId">
                <option value="0">Root category</option>
                @foreach (var subCategory in categoryRepository.GetAll())
                {
                    var selectedAttribute = "";
                    if (parentCategory != null && subCategory.CategoryId == parentCategory.CategoryId)
                    {
                        selectedAttribute = "selected";
                    }
                    <option value="@subCategory.CategoryId" @selectedAttribute>@subCategory.Title</option>
                }
            </select>
        </div>
        <div>
            <input type="submit" value="Save" />
        </div>
    </form>
</fieldset>